<template>
  <div class="wrapper ">
    <el-form class="ur-form" :inline="true" :rules='{}' :model="boxRtu" ref="boxForm">
      <div ref="boxAdd" class="scrollY px-3 pt-3 "  style="max-height: 650px;">
        <!--控制箱信息alpha_dash-->
        <fieldset class="mb-3 pr-0">
          <legend class="w80">控制箱信息</legend>
          <!-- :style="{visibility:(?'visible':'hidden')}"-->
          <el-tooltip  :content="errors.first('boxNo')" :value="errors.has('boxNo')&&scrollVal<80" :manual="true">
            <el-form-item label="控制箱编号" label-width="120px" required :class="{'is-error':errors.has('boxNo')}">
              <el-input class="w150" size="small" v-model="boxRtu.No" v-validate="'required|max:23'" name="boxNo"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="设施权属" label-width="120px" required>
            <el-select class="w150" size="small" v-model="boxRtu.Owner" disabled>
              <el-option v-for="(item,index) in global.BoxOwners" :key="index" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号" label-width="120px" :class="{'is-error':errors.has('Model')}">
<!--            <el-input class="w110" size="small" v-model="boxRtu.Model"></el-input>-->
            <el-select class="w150" size="small" v-model="boxRtu.Model">
              <el-option label="普通箱" value="普通箱"></el-option>
              <el-option label="节能普通箱" value="节能普通箱"></el-option>
              <el-option label="一体箱" value="一体箱"></el-option>
              <el-option label="节能一体箱" value="节能一体箱"></el-option>
              <el-option label="综合电源箱" value="综合电源箱"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="安装类型" label-width="120px" required>
            <el-select class="w150" size="small" v-model="boxRtu.InstallType">
              <el-option v-for="(item,index) in global.BoxTypes" :key="index" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-tooltip :content="errors.first('Manufacturer')" :value="errors.has('Manufacturer')&&scrollVal<150" :manual="true">
            <el-form-item label="生产厂家" label-width="120px" required>
              <el-input style="width: 435px;" size="small" :class="{'is-error':errors.has('Manufacturer')}" v-model="boxRtu.Manufacturer" v-validate="'required|max:23'" name="Manufacturer"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('BoxLngLat')" :value="errors.has('BoxLngLat')" :manual="true">
            <el-form-item label="经纬度" label-width="120px" :class="{'is-error':errors.has('BoxLngLat')}" required>
              <el-input class="" style="width: 320px" size="small" v-model="boxRtu.BoxLngLat" name="BoxLngLat" @change="changeLngLat"></el-input>
              <input type="hidden" v-model="boxRtu.Lng">
              <input type="hidden" v-model="boxRtu.Lat">
              <el-button class="ur-btn ur-btn-primary w110" @click="showMap=true,mapByType='box'"><i class="iconfont icon-gis"></i>获取经纬度</el-button>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('boxArea')" :value="errors.has('boxArea')" :manual="true">
            <el-form-item label="责任区" label-width="120px" required :class="{'is-error':errors.has('boxArea')}">
              <el-select style="width: 435px;" size="small" v-model="boxRtu.AreaId" v-validate="'required'" name="boxArea">
                <el-option v-for="(item,index) in regions" :key="index" :label="item.Name" :value="item.Id"></el-option>
              </el-select>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('Location')" :value="errors.has('Location')" :manual="true">
            <el-form-item label="安装地点" label-width="120px" required :class="{'is-error':errors.has('Location')}">
              <el-input class="" style="width: 435px;" size="small" v-model="boxRtu.Location" v-validate="'required|max:44'" name="Location"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip class="item" :content="errors.first('InstallDate')" :value="errors.has('InstallDate')" :manual="true">
            <el-form-item label="安装时间" label-width="120px" required :class="{'is-error':errors.has('InstallDate')}">
              <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" class="w150" size="small" v-model="boxRtu.InstallDate" v-validate="'required'" name="InstallDate"></el-date-picker>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="道路性质" label-width="120px" required>
            <el-select class="w150" size="small" v-model="boxRtu.RoadNature">
              <el-option v-for="(item,index) in global.RoadNatures" :key="index" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="控制范围" label-width="120px" required>
            <el-select class="w150" size="small" v-model="boxRtu.ControlRange">
              <el-option v-for="(item,index) in global.ControlRanges" :key="index" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-tooltip :content="errors.first('RoadSection')" :value="errors.has('RoadSection')" :manual="true">
            <el-form-item label="所属路段" label-width="120px" required :class="{'is-error':errors.has('RoadSection')}">
              <el-input class="w150" size="small" v-model="boxRtu.RoadSection" v-validate="'required|max:44'" name="RoadSection"></el-input>
            </el-form-item>
          </el-tooltip>

          <el-tooltip class="item" :content="errors.first('RunDate')" :value="errors.has('RunDate')" :manual="true">
            <el-form-item label="投运日期" label-width="120px" required :class="{'is-error':errors.has('RunDate')}">
              <el-date-picker type="date" placeholder="选择日期"   @change="validate" value-format="yyyy-MM-dd" class="w150" size="small"
                              v-model="boxRtu.RunDate"  name="RunDate"></el-date-picker>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="运维单位" label-width="120px" :class="{'is-error':errors.has('Maintenance')}">
            <el-input class="w150" size="small" v-model="boxRtu.Maintenance" name="Maintenance"></el-input>
          </el-form-item>
          <el-form-item label="控制箱状态" label-width="120px" required>
            <el-select class="w150" size="small" v-model="boxRtu.BoxState">
              <el-option v-for="(item,index) in global.BoxStates" :key="index" :label="item" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否有RTU" label-width="120px" >
            <el-select class="w150" size="small" v-model="boxRtu.hasRtu">
              <el-option label="有" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <!--附件multiple="multiple" :label="limits.indexOf('2_03_01_09')!=-1?'附件':''" v-if="limits.indexOf('2_03_01_09')!=-1"-->
          <el-form-item label="选择附件" label-width="120px" label-position="right" class="w300" >
            <div class="p_relative ur-file w150">
<!--              <input type="text" class="text">-->
              <input class=" file" type="file" style="line-height: 20px;" accept=".png,.jpg,jpeg,.pdf" @change="changeFiles">
<!--              <el-button size="small" class="fileBtn ur-btn-round ur-btn ur-btn-primary">预览</el-button>-->
            </div>
            <el-button style="margin-top: 3px;" round class="ur-btn-round ur-btn ur-btn-primary" v-if="files.length" @click="showCarousel=true">
              <i class="iconfont icon-xianshi txt_blue2"></i>图片预览
            </el-button>
          </el-form-item>
        </fieldset>
        <!--RTU基础信息-->
        <fieldset class="mb-3" v-if="boxRtu.hasRtu">
          <legend class="w100">RTU基础信息</legend>
          <el-form-item label="监控方式" label-width="120px" required>
            <el-select class="w150" size="small" v-model="boxRtu.MonitorMode">
              <el-option v-for="(item,index) in global.MonitorModes" :key="index" :label="item" :value="index+1" ></el-option>
            </el-select>
          </el-form-item>
          <el-tooltip class="item" :content="errors.first('DevAddr')" :value="errors.has('DevAddr')" :manual="true">
            <el-form-item label="设备地址" label-width="120px" required :class="{'is-error':errors.has('DevAddr')}">
              <el-input class="w150" size="small" v-model="boxRtu.DevAddr"  v-validate="'required|addr16'" name="DevAddr"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip class="item" :content="errors.first('SimNo')" :value="errors.has('SimNo')" :manual="true">
            <el-form-item label="SIM卡号" label-width="120px" required :class="{'is-error':errors.has('SimNo')}">
              <el-input class="w150" size="small" v-model="boxRtu.SimNo" v-validate="'required|phone'" name="SimNo"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="出线电流互感比" label-width="120px" >
            <el-input class="w150" size="small" v-model="boxRtu.OutlineCt"></el-input>
          </el-form-item>
          <el-tooltip class="item" :content="errors.first('RtuManufacturer')" :value="errors.has('RtuManufacturer')" :manual="true">
            <el-form-item label="生产厂家" label-width="120px" required :class="{'is-error':errors.has('RtuManufacturer')}">
              <el-input style="width: 435px;" size="small" v-model="boxRtu.RtuManufacturer" v-validate="'required|max:44'" name="RtuManufacturer"></el-input>
            </el-form-item>
          </el-tooltip>
        </fieldset>
      </div>
      <div class="text-center my-3">
        <el-button class="ur-btn ur-btn-primary w65" @click="boxRtuSave"><i class="iconfont icon-sure"></i>保存</el-button>
        <el-button class="ur-btn ur-btn-primary w65" @click="reset('boxForm')"><i class="iconfont icon-close3"></i>清空</el-button>
      </div>
    </el-form>

    <!--地图-->
    <el-dialog v-el-drag-dialog title="获取位置" :visible.sync="showMap" width="900px" :modal="false">
      <template v-if="showMap">
        <u-map :iconType="mapByType=='box'?1:3" @getLngLat="getLngLat($event)" :box="boxRtu"></u-map>
      </template>
    </el-dialog>

    <!--图片预览-->
    <div class="w-100 h-100" v-show="showCarousel" style="position: absolute;background: rgba(0,0,0,.4);top:0;left: 0;top:0;z-index: 999;" >
      <file-read :devId="boxId" :files="files" :type="'box'" :fileDelBtn="limits.indexOf('2_03_01_10')!=-1"
      :delFileUrl="'/DevRtu/DelFiles'" @closeFileRead="closeFileRead"></file-read>
    </div>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import api from 'api/api'
  import fetch from 'api/fetch'
  import uMap from 'base/map/map'
  import fileRead from "base/fileRead/fileRead2"
  import elDragDialog from 'directive/el-dragDialog'

  export default {
    directives:{elDragDialog},
    components: {
      uMap,fileRead
    },
    props: {
      boxId:0
    },
    data() {
      return {
        regions:[],
        boxRtu:{Lat:0,Lng:0,BoxLngLat:'0,0',Owner:1,InstallType:1,RoadNature:1,EnergySaving:true,ControlRange:1,Phase:1,BoxState:1,hasRtu:1,hasWell:true,isEnergySave:true,MonitorMode:1,ChannelMode:'2g',NbImei:'',NbDeviceId:'',SimOprators:'电信',SpecMaterial:'水泥'},
        showMap:false,
        scrollVal:0,//根据滚动值 错误信息显示隐藏
        formData:new FormData(),
        files:[],
        height:710,
        showCarousel:false,
      }
    },
    watch: {

    },
    computed: {
      ... mapState({
        clientHeight: state => state.comm.clientHeight,
        clientWidth: state => state.comm.clientWidth,
        limits:state=>state.user.userInfo.limits
      }),
    },
    methods: {
      closeFileRead(v){
        this.showCarousel=false
      },
      changeFiles(){
        let files=event.target.files
        for(let i=0;i<files.length;i++){
          this.formData.append('files',files[i])
        }
      },
      uploadFiles(id){
        api.httpFormData('/DevRtu/SaveFiles?boxId='+id,this.formData)
          .then(r=>{
            this.$emit('close',{})
          })
      },
    /*  delFile(file,index){//删除附件
        this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
          .then(() => {
            api.fetchSimple('/DevRtu/DelFiles',{boxId:this.boxId,fileIds:[file.Id]})
              .then(r=>{
                this.files.splice(index,1)
                if(this.files.length==0) this.showCarousel=false
              })
          })
      },*/
      changeLngLat(lnglat){
        if(lnglat.indexOf(';')!=-1){
          this.boxRtu.Lng=lnglat.split(';')[0]
          this.boxRtu.Lat=lnglat.split(';')[1]
          this.$validator.errors.remove('BoxLngLat')
          return true
        }else{
          this.$validator.errors.add({field: 'BoxLngLat', msg: '格式为经纬;纬度'})
          return false
        }
      },
      validate(value){
        if(value==null) value=''
        let total = new Date(value) - new Date(this.boxRtu.InstallDate)
        if (total < 0 || value == '') {
          if (this.$validator.errors.has('RunDate')) {
            this.$validator.errors.remove('RunDate')
          }
          // let id=this.$validator.fields.find({ name: 'RunDate' })['id']
          this.$validator.errors.add({
            field: 'RunDate',
            msg: '投运时间必填且不能小于安装日期'
          })
          // this.$validator.errors.first('RunDate')
          return false
        } else {
          this.$validator.errors.remove('RunDate')
          return true
        }
      },
      queryArea() {
        let _this=this
        // fetch.queryLikeArea('')
        //   .then(r => {
        //     this.regions = r.data
        //     if (r.data.length) {
        //       this.$set(this.boxRtu, 'AreaId', r.data[0].Id)
        //     }
        //     if(_this.$route.params['id']){
        //       _this.queryBoxRtu(this.$route.params['id'])
        //     }
        //     if(_this.boxId){
        //       _this.queryBoxRtu(_this.boxId)
        //     }
        //   })
      },
      boxRtuSave() {
        // this.$refs['boxRtu'].validate((valid) => {})
        let res=this.validate(this.boxRtu.RunDate)
        if(! res) return
        this.$validator.validateAll().then((res) => {
          // let result = this.formValidata('box')
          if (res) {
            this.boxRtu.RtuInstalled = this.boxRtu.hasRtu ? 1 : 0
            this.boxRtu.WellInstalled = this.boxRtu.hasWell ? 1 : 0
            this.boxRtu.EnergySaving = this.boxRtu.isEnergySave ? 1 : 0
            api.fetch('/DevRtu/Save', this.boxRtu)
              .then(async r => {
                if (r != ''){
                  // this.$message.success('保存成功')
                  if (this.formData.getAll('files').length) {
                    await this.uploadFiles(this.boxId||r.data)
                  }else{
                    this.$emit('close',{})
                  }
                }
              })
          }
        })
      },
      formValidata(form) {
        let len = 0
        let result = true
        this.errors.items.map((r, index, arr) => {
          if (r.field.indexOf(form) != -1) {
            len++
          }
          if (len == 0 && index == arr.length - 1) {
            result = true
          } else if (len != 0 && index == arr.length - 1) {
            result = false
          }
        })
        return result
      },
      reset(formName) {
        // this.$refs[formName].resetFields()
        this.boxRtu={Lat:0,Lng:0,BoxLngLat:'0,0',Owner:1,InstallType:1,RoadNature:1,EnergySaving:true,ControlRange:1,Phase:1,BoxState:2,
          hasRtu:true,hasWell:false,isEnergySave:true,MonitorMode:1,ChannelMode:'2g',NbImei:'', NbDeviceId:'',SimOprators:'电信',SpecMaterial:'水泥'}
      },
      getLngLat(v) {
        if (this.mapByType == 'box') {
          this.boxRtu['BoxLngLat'] = v.lng + '；' + v.lat
          this.boxRtu['Lat'] = v.lat
          this.boxRtu['Lng'] = v.lng
        }else{
          this.boxRtu['WellLngLat'] = v.lng + '；' + v.lat
          this.boxRtu['WellLat'] = v.lat
          this.boxRtu['WellLng'] = v.lng
        }
        this.showMap = false
      },
      queryBoxRtu(id) {
        let _this = this
        fetch.queryBoxById(id)
          .then(r => {
            let data = r.data[0]
            _this.boxRtu = data
            _this.files=r.Files||[]
            this.$set(this.boxRtu, 'AreaId', r.data[0].AreaId)
            this.$set(this.boxRtu, 'hasRtu', data.RtuInstalled == 1 ? true : false)
            this.$set(this.boxRtu, 'hasWell', data.WellInstalled==1? true : false)
            this.$set(this.boxRtu, 'isEnergySave', data.EnergySaving==1? true : false)
            _this.$set(this.boxRtu, 'BoxLngLat', data.Lng + ';' + data.Lat)
            _this.$set(this.boxRtu, 'WellLngLat', data.WellLng + ';' + data.WellLat)
            //查询开关
          })
      }
    },
    created() {
      this.$set(this.boxRtu,'RunDate',api.formatDate(new Date()))
      this.$set(this.boxRtu,'InstallDate',api.formatDate(new Date()))
      this.$set(this.boxRtu,'RtuInstallDate',api.formatDate(new Date()))
      this.queryArea()
    },
    mounted() {
      let box= this.$refs.boxAdd
      box.addEventListener('scroll', ()=>{
        this.scrollVal =box.scrollTop
      })
    }
  }
</script>
<style  lang="stylus" rel="stylesheet/stylus">

</style>
